from django.shortcuts import render, redirect

import AppManager.Mysql
import HostManager.SSH
from OpManager import settings
from datetime import datetime
import re

InstallLogsDict = {}


# 三种日志类型：UserLog HostLog OpLog
def log(text: str, logtype='SysLog', user='sys'):
    now = datetime.now()
    logfile = settings.logtype[logtype]
    with open(logfile, "a") as Log:
        text = text.replace("\r\n", "\\r\\n")
        text = text.replace("[", "【")
        text = text.replace("]", "】")
        logtext = "[" + now.strftime('%Y-%m-%d %H:%M:%S') + "] [" + user + "] : [" + text + "]\n"
        Log.write(logtext)


# 获取对应类型的日志，返回列表
def getlog(logtype):
    loglist = []
    i = 0
    try:
        with open(settings.logtype[logtype]) as logfile:
            log = logfile.readline()
            while log:
                i += 1
                logitem = list(re.findall(r"\[(.*)\].\[(.*)\]\s:\s\[(.*)\]", log, re.S)[0])
                logitem[2] = logitem[2].replace("\\r\\n", "\n")
                logitem[2] = logitem[2].replace("【", "[")
                logitem[2] = logitem[2].replace("】", "]")
                loglist.insert(0, logitem)
                # loglist.append(logitem)
                log = logfile.readline()
                if i > 2000:
                    loglist.pop()
    except FileNotFoundError as e:
        print(e)
        loglist.append(['未找到日志文件', settings.logtype[logtype]])
    finally:
        return loglist


# 系统日志页面
@settings.auth(AuthType="Logs", AuthNum=3)
def SystemLogs(requests):
    logdict = getlog("SysLog")
    context = {
        "logdict": logdict
    }

    return render(requests, 'SystemLogs.html', context)


@settings.auth(AuthType="Logs", AuthNum=4)
def UserLogs(requests):
    logdict = getlog("UserLog")
    context = {
        "logdict": logdict
    }
    return render(requests, 'UserLogs.html', context)


@settings.auth(AuthType="Logs", AuthNum=5)
def InstallLogs(requests):
    context = {
        "InstallLogsDict": InstallLogsDict
    }
    return render(requests, 'InstallLogs.html', context)


# 更新安装日志
@settings.auth(AuthType="Logs", AuthNum=5)
def reInstallLogs(requests, hostname):
    try:
        # 获取主机的信息
        sql = "SELECT * FROM `host` where hostname='%s'" % hostname
        host = AppManager.Mysql.MysqlPool(sql, 1)
        sql = "SELECT * FROM `host_dev` where hostname='%s'" % hostname
        hostdev = AppManager.Mysql.MysqlPool(sql, 1)
        HostData = {
            "hostname": hostname,
            "host": host["ip"],
            "port": host["ssh_port"],
            "username": hostdev["Suser"],
            "password": hostdev["Spasswd"]
        }
        getInstallLogs(HostData)
    except Exception as e:
        print("Logs_views.reInstallLogs", type(e), e)
    return redirect('/logs_install')


# 为了解决依赖循环，只好放到这里来了
from HostSetting import views as HS_views


# 获取所有主机的应用安装日志
def getAllInstallLogs():
    try:
        # 获取主机的信息
        sql = "SELECT * FROM `host`"
        hosts = AppManager.Mysql.MysqlPool(sql, 99)
        sql = "SELECT * FROM `host_dev`"
        hostdevs = AppManager.Mysql.MysqlPool(sql, 99)
        i = 0
        for host in hosts:
            HostData = {
                "hostname": host["hostname"],
                "host": host["ip"],
                "port": host["ssh_port"],
                "username": hostdevs[i]["Suser"],
                "password": hostdevs[i]["Spasswd"]
            }
            i += 1
            getInstallLogs(HostData)
    except Exception as e:
        print("getAllInstallLogs", type(e), e)


# 获取安装日志
def getInstallLogs(HostData):
    rootPath = HS_views.AppConfig["TmpDir"]
    # 将应用名：命令作为键值对存进字典
    commanddict = {}
    # 命令直接放到命令执行列表
    commandlist = []
    # 将应用名：结果作为键值对存进字典
    global InstallLogsDict
    InstallLogsDict[HostData["hostname"]] = {}
    for appname in HS_views.FileName:
        tmpname = appname + "_install.log"
        tmpcommand = "cat %s/%s" % (rootPath, tmpname)
        commanddict[appname] = tmpcommand
        commandlist.append(tmpcommand)
    res = HostManager.SSH.SshComm(HostData["host"], HostData["port"], HostData["username"], HostData["password"], commandlist)
    i = 0
    for appname, command in commanddict.items():
        InstallLogsDict[HostData["hostname"]][appname] = {}
        if res[command]["stdout"]:
            if not i:
                i += 1
                InstallLogsDict[HostData["hostname"]][appname]["active"] = " active"
                InstallLogsDict[HostData["hostname"]][appname]["show"] = " active show"
            InstallLogsDict[HostData["hostname"]][appname]["log"] = res[command]["stdout"]
        else:
            InstallLogsDict[HostData["hostname"]][appname]["active"] = "disabled"


print("初始化获取安装日志")
getAllInstallLogs()
